<template>
  <div class="knowledge-checkbox">
    <div class="header">
      <h3>选择知识库</h3>
      <el-button link type="primary" @click="toggleSelectAll">
        {{ isAllSelected ? '取消全选' : '全选' }}
      </el-button>
    </div>
    
    <div class="checkbox-list">
      <el-checkbox-group v-model="selectedKnowbases">
        <div v-for="knowbase in knowledgeBases" :key="knowbase.id" class="checkbox-item">
          <el-checkbox :label="knowbase.know_base_id">
            {{ knowbase.know_base_name }}
          </el-checkbox>
          <span class="knowbase-id">ID: {{ knowbase.know_base_id }}</span>
        </div>
      </el-checkbox-group>
    </div>
    
    <div class="selected-count">
      已选择 {{ selectedKnowbases.length }} 个知识库
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { getKnowledgeBases } from '@/services/rag';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue']);

const knowledgeBases = ref([]);
const selectedKnowbases = ref([]);
const loading = ref(false);

// 计算是否全选
const isAllSelected = computed(() => {
  return selectedKnowbases.value.length === knowledgeBases.value.length && knowledgeBases.value.length > 0;
});

// 获取知识库列表
const fetchKnowledgeBases = async () => {
  loading.value = true;
  try {
    const response = await getKnowledgeBases({
      page: 1,
      page_size: 100
    });
    console.log(response.data)
    knowledgeBases.value = response.data.list || [];
  } catch (error) {
    console.error('获取知识库列表失败:', error);
    ElMessage.error('获取知识库列表失败');
  } finally {
    loading.value = false;
  }
};

// 全选/取消全选
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedKnowbases.value = [];
  } else {
    selectedKnowbases.value = knowledgeBases.value.map(kb => kb.know_base_id);
  }
};

// 监听选择变化
watch(selectedKnowbases, (newValue) => {
  emit('update:modelValue', newValue);
});

// 监听外部modelValue变化
watch(() => props.modelValue, (newValue) => {
  selectedKnowbases.value = newValue;
});

onMounted(() => {
  fetchKnowledgeBases();
  selectedKnowbases.value = props.modelValue;
});
</script>

<style scoped>
.knowledge-checkbox {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  background: white;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.checkbox-list {
  max-height: 200px;
  overflow-y: auto;
}

.checkbox-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.checkbox-item:last-child {
  border-bottom: none;
}

.knowbase-id {
  font-size: 12px;
  color: #909399;
}

.selected-count {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e0e0e0;
  font-size: 14px;
  color: #606266;
  text-align: center;
}
</style>